<template>
  <div class="order-selector">
    <el-select 
      :model-value="selectedOrder" 
      placeholder="请选择要追踪的订单" 
      clearable 
      filterable
      :filter-method="filterMethod"
      remote
      @update:model-value="handleOrderChange"
      style="width: 350px;"
      size="default"
    >
      <template #empty>
        <div class="empty-content">
          <el-empty description="暂无订单数据" :image-size="60">
            <el-button type="primary" size="small">刷新列表</el-button>
          </el-empty>
        </div>
      </template>
      
      <el-option
        v-for="item in filteredOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
        <div class="option-item">
          <div class="option-header">
            <span class="order-number">{{ item.order?.orderNumber }}</span>
            <el-tag 
              :type="getStatusType(getOrderStatus(item.order))" 
              size="small"
              class="status-tag"
            >
              {{ getStatusText(getOrderStatus(item.order)) }}
            </el-tag>
          </div>
          <div class="option-detail">
            <span class="route-text">
              {{ getCityFromAddress(item.order?.senderAddress) }} → 
              {{ getCityFromAddress(item.order?.receiverAddress) }}
            </span>
            <span class="fee-text">¥{{ item.order?.totalFee }}</span>
          </div>
        </div>
      </el-option>
    </el-select>
    

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { DeliveryOrder } from '@/api/user'

interface OrderOption {
  value: string
  label: string
  order?: DeliveryOrder
}

interface Props {
  selectedOrder: string
  orderOptions: OrderOption[]
}

interface Emits {
  (e: 'update:selectedOrder', value: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const searchKeyword = ref('')
const filteredOptions = ref<OrderOption[]>([])

// 计算属性已移除

// 初始化筛选选项
filteredOptions.value = props.orderOptions

// 方法
const getCityFromAddress = (address?: string): string => {
  if (!address) return ''
  const match = address.match(/^(.{2})/)
  return match ? match[1] : address.substring(0, 2)
}

// 获取订单状态（处理不同角色的数据结构差异）
const getOrderStatus = (order?: any): number => {
  if (!order) return -1 // 使用-1表示无效状态，避免与状态0混淆
  
  // 配送员数据使用status字段，普通用户数据使用orderStatus字段
  let status = order.status !== undefined ? order.status : order.orderStatus
  
  // 确保状态是数字类型
  if (typeof status === 'string') {
    status = parseInt(status, 10)
  }
  
  // 如果状态是0，也是有效的（待揽件状态）
  if (status === 0 || status > 0) {
    console.log('订单状态:', order.orderNumber, '状态值:', status)
    return status
  }
  
  console.warn('订单状态无效:', order.orderNumber, '原始状态:', order.status, '订单状态:', order.orderStatus)
  return -1 // 返回-1表示无效状态
}

const getStatusText = (status?: number): string => {
  if (status === undefined || status === null || status === -1) return '未知'
  const statusMap: Record<number, string> = {
    0: '待揽件',
    1: '待发货',
    2: '运输中',
    3: '已送达',
    4: '已签收'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status?: number): 'info' | 'primary' | 'warning' | 'success' | 'danger' => {
  if (status === undefined || status === null || status === -1) return 'info'
  const typeMap: Record<number, 'info' | 'primary' | 'warning' | 'success' | 'danger'> = {
    0: 'info',
    1: 'warning',
    2: 'primary',
    3: 'warning',
    4: 'success'
  }
  return typeMap[status] || 'info'
}

const filterMethod = (query: string) => {
  searchKeyword.value = query
  if (!query) {
    filteredOptions.value = props.orderOptions
    return
  }
  
  const keyword = query.toLowerCase()
  filteredOptions.value = props.orderOptions.filter(option => {
    return (
      option.label.toLowerCase().includes(keyword) ||
      (option.order?.orderNumber && option.order.orderNumber.toLowerCase().includes(keyword)) ||
      (option.order?.senderName && option.order.senderName.toLowerCase().includes(keyword)) ||
      (option.order?.receiverName && option.order.receiverName.toLowerCase().includes(keyword))
    )
  })
}

const handleOrderChange = (value: string) => {
  emit('update:selectedOrder', value)
}



// 监听订单选项变化
import { watch } from 'vue'
watch(() => props.orderOptions, (newOptions) => {
  if (!searchKeyword.value) {
    filteredOptions.value = newOptions
  } else {
    filterMethod(searchKeyword.value)
  }
}, { immediate: true })
</script>

<style scoped>
.order-selector {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.empty-content {
  padding: 20px;
}

.option-item {
  padding: 8px 0;
}

.option-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.order-number {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.status-tag {
  flex-shrink: 0;
}

.option-detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.route-text {
  flex: 1;
}

.fee-text {
  color: #e6a23c;
  font-weight: 600;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .order-selector {
    width: 100%;
  }
  
  .el-select {
    width: 100% !important;
  }
  
  .option-detail {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>